package net.mikoo.seals.biz.service.impl;

import java.io.InputStream;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import net.mikoo.seals.biz.common.BaseServices;
import net.mikoo.seals.biz.manager.OssManager;
import net.mikoo.seals.biz.mapper.UpfileMapper;
import net.mikoo.seals.biz.service.UpfileServices;
import net.mikoo.seals.common.exception.UploadException;
import net.mikoo.seals.model.Upfile;
import net.mikoo.seals.utils.Base64Util;

@Service
public class UpfileServicesImpl extends BaseServices implements UpfileServices {

	Logger logger = LoggerFactory.getLogger(UpfileServicesImpl.class);
	
	
	@Autowired
	private OssManager ossManager;
	

	@Autowired
	private UpfileMapper upfileMapper;

	@Value(value="${aliyun.oss.bucket}")
	private String baseUrl;
	
	@Override
	public Upfile upload(Upfile upfile) {
		
		//Long fileSizeLimit =10240l;
		//String imgLimitTypes= "*.jpg;*.jpeg;*.gif;*.bmp;*.png";
		

//		if (upfile == null) {
//			throw new ParametersException("upfile is null!");
//		}

//		if (!imgLimitTypes.contains(upfile.getExtName())) {
//			throw new ParametersException(upfile.getExtName() + " Not allowed to upload");
//		}

		// 判断是否 超出大小
//		if (fileSizeLimit < upfile.getFileSize() / 1024) {
//			throw new ParametersException("文件" + upfile.getFileName() + "大小为" + upfile.getFileSize() + "超过设置的2M！");
//		}
		try {
			
			InputStream is = null;
			if(StringUtils.isNotBlank(upfile.getDataURL())) {
				//Base64Util
				is = Base64Util.transform2Image(upfile.getDataURL());
			}else {
				CommonsMultipartFile file = upfile.getFile();
				is = file.getInputStream();
			}
			
			upfile.setBaseUrl("");
			ossManager.upload(upfile.getFileUrl(), is);
			upfile.setFileUrl(baseUrl + "/" + upfile.getFileUrl());
			upfileMapper.insert(upfile);
			return upfile;
		} catch (Exception e) {
			logger.error("",e);
			throw new UploadException();
		}
		
		

	}

}
